package com.robusta.app.model.spreadsheet.templates;

import com.google.common.io.Resources;
import com.robusta.app.domain.spreadsheet.templates.Metadata;
import com.robusta.app.model.persistence.AuditListener;
import com.robusta.spreadsheet.describe.WorkbookInfo;
import com.robusta.spreadsheet.describe.WorkbookInfoFactory;
import org.apache.commons.lang3.builder.ToStringBuilder;

import javax.persistence.*;
import javax.xml.bind.JAXBException;
import java.io.IOException;
import java.io.InputStream;

import static com.google.common.base.Preconditions.checkState;

@Entity @Table(name = "WORKBOOK_TEMPLATE") @EntityListeners(AuditListener.class)
public class PersistableMetadata implements Metadata{
    @Id
    @Column(name = "TEMPLATE_ID", nullable = false)
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;
    @Column(name = "TEMPLATE_NAME", nullable = false)
    private String name;
    @Column(name = "TEMPLATE_VERSION", nullable = false)
    private String version;


    public PersistableMetadata(String name, String version) {
        this.name = name;
        this.version = version;
    }

    protected PersistableMetadata() {} // pour JPA.

    @Override
    public String templateName() {
        return name;
    }

    @Override
    public String version() {
        return version;
    }

    @Override
    public String templateXmlFileName() {
        checkState(name != null, "Persistable object has an un-initialized state");
        checkState(version != null, "Persistable object has an un-initialized state");
        return String.format("%s.%s.xml", name, version);
    }

    @Override
    public InputStream templateXmlContent() throws IOException {
        return Resources.getResource(PersistableMetadata.class, templateXmlFileName()).openStream();
    }

    @Override
    public WorkbookInfo templateAsWorkbookInfo() throws IOException, JAXBException {
        return WorkbookInfoFactory.buildFrom(templateXmlContent());
    }

    @Override
    public String toString() {
        return ToStringBuilder.reflectionToString(this);
    }
}
